﻿
//这个是新的
$.fn.json_serialize = function () {
    var a = this.serializeArray();
    var $radio = $('input[type=radio],input[type=checkbox]', this);
    $.each($radio, function () {
        if ($("input[name='" + this.name + "']").is(':checked')) {
            console.log(this.name + " is checked!");
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = true;
                    break;
                }
            }
        } else {
            var find = false;
            for (var k = 0; k < a.length; k++) {
                if (a[k].name == this.name) {
                    a[k].value = false;
                    find = true;
                    break;
                }
            }
            if (!find) {
                a.push({ name: this.name, value: false });
            }
        }
    });
    var $num = $('input[type=number]', this);
    $.each($num, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                a[k].value = Number(a[k].value);
                break;
            }
        }
    });

    var $snum = $('select', this);
    $.each($snum, function () {
        for (var k = 0; k < a.length; k++) {
            if (a[k].name == this.name) {
                var valread = a[k].value.toString();
                if (/[0-9]/g.test(valread)) {
                    a[k].value = Number(a[k].value);
                }
                break;
            }
        }
    });
    return a;
};

$.fn.parseForm = function () {
    let serializeObj = {};
    let array = this.json_serialize();
    let str = this.serialize();
    $(array).each(function () {
        if (serializeObj[this.name]) {
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value);
            } else {
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value;
        }
    });
    return serializeObj;
};
//————————————————===================

/**
 * 
 * @param {*} obj 
 */
function _bindelement(obj) {
    for (var key in obj) {
        var objdom = $("[name=" + key + "]");
        if (objdom.length > 0) {
            var tagname = objdom[0].tagName;
            if (tagname == "INPUT") {
                var type = objdom[0].type;
                if (type == "checkbox") {
                    // console.log(obj[key]);
                    if (obj[key] || obj[key] === 1) {
                        objdom.prop("checked", true);
                        objdom.parent().addClass("checked");
                    }else{
                        objdom.prop("checked", false);
                        objdom.parent().removeClass("checked");
                    }
                } else {
                    objdom.val(obj[key]);
                }
            } else if (tagname == "SELECT") {
                objdom.val(obj[key]);
            } else if (tagname == "TEXTAREA") {
                objdom.val(obj[key]);
            }
            else if (tagname == "IMG") {
                objdom.attr('src', obj[key]);
            } else if (tagname == "DIV") {
                objdom.html(obj[key]);
            }
        }
    }
}

/**
 * 
 * @param {*} httpurl 
 * @param {*} _async 
 * @param {*} callback 
 */
function _apiget(httpurl, _async, callback) {

    var loadid = 0;
    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);

    $.ajax({
        //提交数据的类型 POST GET
        type: "GET",
        //提交的网址
        url: httpurl,
        async: _async,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: { "token": readToken() },
        //在请求之前调用的函数
        beforeSend: function (request) {
            // console.log("beforesend");
        },
        //成功返回之后调用的函数
        success: function (data) {
            // console.log("success");
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            // console.log("complete");
            ajaxcompleted = true;
            _actioncallback(XMLHttpRequest, loadid, callback);
        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            console.log("error");
        }
    });
}

var _waitloading = 500;

function _apipost(httpurl, async, data, callback) {
    var loadid = 0;
    // if (typeof (layer) != "undefined") {
    //     loadid = layer.load();
    // }

    var ajaxcompleted = false;
    var tickevent = function () {
        if (!ajaxcompleted) {
            if (typeof (layer) != "undefined") {
                loadid = layer.load();
            }
        }
    }
    setTimeout(tickevent, _waitloading);

    $.ajax({
        //提交数据的类型 POST GET
        type: "POST",
        //提交的网址
        url: httpurl,
        async: async,
        //提交的数据
        data: data,
        //返回数据的格式
        datatype: "jsonp",//"xml", "html", "script", "json", "jsonp", "text".
        headers: {
            "token": readToken()
        },
        contentType: "application/json; charset=UTF-8",
        //在请求之前调用的函数
        beforeSend: function (request) {
            //request.setRequestHeader("order", order);
        },
        //成功返回之后调用的函数
        success: function (data) {
            //console.log("执行到了success");
        },
        //调用执行后调用的函数
        complete: function (XMLHttpRequest, textStatus) {
            //console.log(XMLHttpRequest);
            ajaxcompleted = true;
            _actioncallback(XMLHttpRequest, loadid, callback);
        },
        //调用出错执行的函数
        error: function () {
            //请求出错处理
            //console.log("执行到了error");
        }
    });
}

function _actioncallback(XMLHttpRequest, loadid, callback) {
    try {
        if (XMLHttpRequest.status == 401) {
            if (typeof (layer) != "undefined") {
                layer.msg("当前操作需要登录！", { time: 1500 }, function () {
                    window.parent.location.href = "/page/login/index.html?t=" + (new Date()).getTime();
                });
            } else {
                window.parent.location.href = "/page/login/index.html?t=" + (new Date()).getTime();
            }
        } else if (XMLHttpRequest.status == 204) {
            if (typeof (layer) != "undefined") {
                layer.msg("查询数据为空");
            } else {
                alert("查询数据为空");
            }
        } else {
            var responsestr = XMLHttpRequest.responseText;
            if (XMLHttpRequest.status == 200) {
                if (responsestr.indexOf("{") >= 0) {
                    try {
                        callback(XMLHttpRequest.status, JSON.parse(responsestr));
                    } catch (ejson) {
                        callback(XMLHttpRequest.status, responsestr);
                    }

                } else {
                    callback(XMLHttpRequest.status, responsestr);
                }
            }else if(XMLHttpRequest.status==400){
                if (responsestr.indexOf("{") >= 0) {
                    var errinfo = JSON.parse(responsestr);
                    if(errinfo.errors){
                        var errstr ="";
                        for(var key in errinfo.errors){
                            errstr = errinfo.errors[key][0];
                        }
                        if(errstr && errstr.length>0){
                            layer.msg(errstr);
                        }
                    }
                    callback(XMLHttpRequest.status, errinfo);
                } else {
                    callback(XMLHttpRequest.status, responsestr);
                }
            } else {
                if (responsestr.indexOf("{") >= 0) {
                    var errinfo = JSON.parse(responsestr);
                    if (errinfo.message) {
                        if (typeof (layer) != "undefined") {
                            layer.msg(errinfo.message);
                        } else {
                            alert(errinfo.message);
                        }
                    }else if(errinfo.errors){

                    }
                    callback(XMLHttpRequest.status, errinfo);
                } else {
                    callback(XMLHttpRequest.status, responsestr);
                }
            }
        }
    } catch (err) {
        console.log(err.message);
    }finally{

    }
    if (loadid > 0) {
        if (typeof (layer) != "undefined") {
            layer.close(loadid);
        }
    }
}
/**
 * 
 * @param {*} key 
 * @returns 
 */
function _apigetquery(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}

/**
 * 
 * @returns 
 */
function readToken() {
    var _token = _locReadData("webtoken");
    if (_token != null) {
        return _token;
    } else {
        return "";
    }
}
/**
 * 
 * @param {*} sval 
 */
function saveToken(sval) { if (sval.length > 0) { _locSaveData("webtoken", sval); } else { localStorage.removeItem("webtoken"); } }

/**
 * 
 * @param {*} skey 
 * @param {*} sval 
 */
function _locSaveData(skey, sval) { localStorage.setItem(skey, sval); }

/**
 * 
 * @param {*} skey 
 * @returns 
 */
function _locReadData(skey) {
    return localStorage.getItem(skey);
}

//=====================================

/**
 * 打开编辑页面
 * @param {any} title
 * @param {any} url
 * @param {any} id
 * @param {any} w
 * @param {any} h
 */
function _showedit(title, url, id, w, h) {

    if (url.indexOf('?') > 0) {
        layer_show(title, url + "&id=" + id, w, h);
    } else {
        layer_show(title, url + "?id=" + id, w, h);
    }
}

/**
 * 
 * @param {*} title 
 * @param {*} url 
 * @param {*} w 
 * @param {*} h 
 */
function _showwindow(title, url, w, h) {
    layer_show(title, url, w, h);
}

/**
 * 打开新增页面
 * @param {any} title
 * @param {any} url
 * @param {any} w
 * @param {any} h
 */
function _showadd(title, url, w, h) {
    layer_show(title, url, w, h);
}

/**
 * 
 * @param {*} fmt 
 * @returns 
 */
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

/**
 * 运行状态
 * @returns 
 */
Number.prototype.RunState=function(){
    if(this == 0){ return '<span style="color:#999;">等待</span>';}
    if(this == 1){ return '<span style="color:#00ff47;">执行中</span>';}
    if(this == 2){ return '<span style="color:#888;">取消</span>';}
    if(this == 3){ return '<span style="color:green;">成功</span>';}
    if(this == 4){ return '<span style="color:red;">失败</span>';}
    if(this == 5){ return '<span style="color:red">错误</span>';}
    if(this == 6){ return '<span style="color:red">停止</span>';}
    if(this == 7){ return '<span style="color:#888">未知</span>';}
    if(this == 8){ return '<span style="color:red">异常</span>';}
    return "未知";
}

/**
 * 
 * @returns 
 */
Number.prototype.BuildState = function () {
    if (this == 0) {
        return '<span style="color:#888">待构建</span>';
    }
    if (this == 1) {
        return '<span style="color:green">构建中</span>';
    }
    if (this == 3) {
        return "构建成功";
    }
    return "未知";
}
/**
 * 
 * @returns 
 */
Number.prototype.FileModel = function () {
    if (this == 0) {
        return '<span style="color:red">静态模式</span>';
    }
    if (this == 1) {
        return '<span style="color:blue">源码模式</span>';
    }
    if (this == 2) {
        return '<span style="color:green">发布模式</span>';
    }
    return "未知";
}


/**
 * 
 * @param {*} async 
 */
function _readproject(async) {
    _apiget("/api/spider/projectInfo?page=1&size=200", async, function (code, obj) {
        // $("[name=projectId]").empty();
        if (code == 200) {

            var datas = obj.items;
            var htmlStr = "";
            for (var k = 0; k < datas.length; k++) {
                var item = datas[k];
                htmlStr += '<option value="' + item.id + '">' + item.name + '(' + item.code + ')</option>';
            }
            $("[name=projectId]").append(htmlStr);
        }
    });
}
/**
 * 
 * @param {*} async 
 */
function _readstore(async) {
    _apiget("/api/spider/storeInfo?page=1&size=200", async, function (code, obj) {
        // $("[name=storeId]").empty();
        if (code == 200) {

            var datas = obj.items;
            var htmlStr = "";
            for (var k = 0; k < datas.length; k++) {
                var item = datas[k];
                htmlStr += '<option value="' + item.id + '">' + item.name + '</option>';
            }
            $("[name=storeId]").append(htmlStr);
        }
    });
}

function _readservice(async) {
    _apiget("/api/spider/serviceInfo?page=1&size=200", async, function (code, obj) {
        // $("[name=serviceId]").empty();
        if (code == 200) {
            var datas = obj.items;
            var htmlStr = "";
            for (var k = 0; k < datas.length; k++) {
                var item = datas[k];
                htmlStr += '<option value="' + item.id + '">' + item.name + '(' + item.code + ')</option>';
            }
            $("[name=serviceId]").append(htmlStr);
        }
    });
}

function _readmodel(async) {
    _apiget("/api/spider/modelInfo?page=1&size=200", async, function (code, obj) {
        $("[name=modelId]").empty();
        if (code == 200) {
            var datas = obj.items;
            var htmlStr = "";
            for (var k = 0; k < datas.length; k++) {
                var item = datas[k];
                htmlStr += '<option value="' + item.id + '">' + item.code + '</option>';
            }
            $("[name=modelId]").append(htmlStr);
        }
    });
}

function _readlinux(async, elcname) {
    _apiget("/api/spider/linuxInfo?page=1&size=200", async, function (code, obj) {
        // $("[name=linuxId]").empty();
        if (code == 200) {
            var datas = obj.items;
            var htmlStr = "";
            for (var k = 0; k < datas.length; k++) {
                var item = datas[k];
                htmlStr += '<option value="' + item.id + '">' + item.name + '</option>';
            }
            $("[name=linuxId]").append(htmlStr);
        }
    });
}

/**
 * 任务类型
 * @returns 
 */
Number.prototype.OrderType = function () {
    if (this == 0) {
        return "未知";
    }
    if (this == 1) {
        return "扩容";
    }
    if (this == 2) {
        return "缩减";
    }
    if (this == 3) {
        return "升级";
    }
    if (this == 4) {
        return "登仓";
    }
    if (this == 5) {
        return "建仓";
    }
    if (this == 6) {
        return "重启";
    }
    if (this == 7) {
        return "停止";
    }
    if (this == 8) {
        return "构建";
    }
    if (this == 9) {
        return "灰升";
    }
    if (this == 10) {
        return "检查";
    }
    if (this == 11) {
        return "更配";
    }
    if (this == 12) {
        return "伸缩";
    }
    return "未知";

}




/**
 * 是否移动端
 * @returns 
 */
function _ismobile() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsAndroid || bIsMidp || bIsUc7 || bIsUc || bIsCE || bIsWM) {
        return true;
    }
    return false;
}


/**
 * 重启容器
 * @param {容器ID} id 
 */
function _actionapprestart(id) {
    _apipost("/api/spider/manage/" + id + "/appRestart", true, "", function (code, obj) {
        if (code == 200) {
            layer.msg("计划已提交！");
        }
    });
}

/**
 * 停止一个容器 如果是系统的项目，则会去除对应的nginx等 docker stop && docker rm
 * @param {容器ID} id 
 */
function _actionappstop(id) {
    _apipost("/api/spider/manage/" + id + "/appStop", true, "", function (code, obj) {
        if (code == 200) {
            layer.msg("计划已提交！");
        }
    });
}

/**
 * 刷新一个容器的运行状态
 * @param {容器ID} id 
 */
function _actionapprefush(id) {
    _apipost("/api/spider/manage/" + id + "/appRefush", true, "", function (code, obj) {
        if (code == 200) {
            layer.msg("计划已提交！");
        }
    });
}

/**
 * 删除一个容器 目前没有启用
 * @param {容器ID} id 
 */
function _actionappdelete(id,linuxid) {
    _apipost("/api/spider/manage/" + id + "/appDelete?linuxid="+linuxid, true, "", function (code, obj) {
        if (code == 200) {
            layer.msg(obj);
        }
    });
}

/**
 * 删除某一个服务器上的镜像
 * @param {*} linuxid 
 * @param {*} id 
 */
function _actionremoveimage(linuxid, id) {
    _apipost("/api/spider/manage/" + id + "/ExecDockerRmiById?linuxid=" + linuxid, true, "", function (code, obj) {
        if (code == 200) {
            layer.msg("计划已提交！");
        }
    });
}

/**
 * 获取随机字符串
 * @returns 
 */
function _funcrandomstr(elc) {
    len = 32;
    var $chars = 'qwertyuiopasdfghjklzxcvbnm123456789';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    $(elc).parent().find('input[type=text]').val(pwd);
}

/**
 * 根据javascript text/html构建对象，最多支持3级
 * @param {*} html 
 * @param {*} obj 
 * @returns 
 */
function _buildtemplate(html, obj) {
    //\[([^\[\]]*?)\]
    var reg = new RegExp("\\[([^\\[\\]]*?)\\]", 'igm');
    // var html = document.getElementById("orderdetailhtml").innerHTML;
    var _innerhtml = html.replace(reg, function (node, key) {
        if (key.indexOf(":") > 0) {
            var keys = key.split(':');
            switch (keys.length) {
                case 2: {
                    if (obj[keys[0]] != null) {
                        return obj[keys[0]][keys[1]]
                    } else {
                        return "";
                    }
                };
                case 3:
                    {
                        if (obj[keys[0]] != null) {
                            if (obj[keys[0]][keys[1]] != null) {
                                return obj[keys[0]][keys[1]][keys[2]];
                            } else {
                                return "";
                            }
                        } else {
                            return "";
                        }
                    };
                case 4:
                    {
                        if (obj[keys[0]] != null) {
                            if (obj[keys[0]][keys[1]] != null) {
                                if (obj[keys[0]][keys[1]][keys[2]] != null) {
                                    return obj[keys[0]][keys[1]][keys[2]][keys[3]];
                                } else {
                                    return "";
                                }
                            } else {
                                return "";
                            }
                        } else {
                            return "";
                        }
                    };
                default: return obj[keys[0]][keys[1]];
            }
        } else {
            return obj[key];
        }
    });
    return _innerhtml;
}


/**
 * 前端验证
 * @param {*} elcselect 
 * @returns 
 */
function _beforeValidity(elcselect) {

    var findvalid = true;
    var fileds = $(elcselect)[0].querySelectorAll(":invalid");
    for (var k = 0; k < fileds.length; k++) {
        var namestr = fileds[k].name;
        var valinfo = fileds[k].validity;
        if (!valinfo.valid) {
            findvalid = false;
            $(elcselect + " [name=" + namestr + "]").focus();
            if (valinfo.valueMissing) {
                layer.tips('当前项必须填写', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }
            if (valinfo.typeMismatch) {
                layer.tips('输入的数据类型不匹配，请按需输入', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }

            if (valinfo.patternMismatch) {
                layer.tips('输入的数据格式不匹配，请按需输入', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }

            if (valinfo.tooLong) {
                layer.tips('输入的数据位数过大，请按需输入', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }
            if (valinfo.tooShort) {
                layer.tips('输入的数据位数不足，请按需输入', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }

            if (valinfo.rangeOverflow) {
                layer.tips('输入的数据过大，请按需输入', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }

            if (valinfo.rangeUnderflow) {
                layer.tips('输入的数据过小，请按需输入', elcselect + " [name=" + namestr + "]", { tipsMore: true,tips:1 }, 1);
            }
        }
    }
    return findvalid;
}
